package cn.hwadee.muying.controller.sys;


import cn.hwadee.muying.commons.base.BaseController;
import cn.hwadee.muying.commons.constant.ConstantRole;
import cn.hwadee.muying.commons.constant.ConstantWebContext;
import cn.hwadee.muying.commons.jqgrid.GridResult;
import cn.hwadee.muying.commons.page.MyPage;
import cn.hwadee.muying.commons.utils.Md5Utils;
import cn.hwadee.muying.dto.Client;
import cn.hwadee.muying.entity.ClientInfo;
import cn.hwadee.muying.entity.Role;
import cn.hwadee.muying.entity.User;
import cn.hwadee.muying.service.*;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * <p>
 * 用户相关信息 前端控制器
 * </p>
 *
 * @author Tony
 * @since 2018-04-17
 */
@Controller
@RequestMapping("/sys/user")
public class UserController extends BaseController {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private OrganizationService orgService;
    @Autowired
    private ClientService clientService;
    @Autowired
    private ClientInfoService clientInfoService;
    @ModelAttribute("user")
    public User get(@RequestParam(required = false, value = "id") Long id) throws Exception {
        if (id != null && id > 0) {
            return userService.selectById(id);
        } else {
            return new User();
        }
    }

    @RequiresPermissions("sys:user:list")
    @RequestMapping(value = "/list", produces = "text/html;charset=utf-8", method = RequestMethod.GET)
    public String list(Model model) throws Exception{
        return "/sys/user/list";
    }

    @ResponseBody
    @RequiresPermissions("sys:user:list")
    @RequestMapping(value = "/list.json", produces = "application/json;charset=utf-8")
    public GridResult list(String keyword) throws Exception{
        MyPage<User> page = getPage();
        page = userService.list(page,getCurrentUser(),keyword);
        GridResult result = new GridResult(page.getCurrent(),page.getPages(),page.getCurrent(),page.getRecords());
        return result;
    }

    @RequiresPermissions("sys:user:edit")
    @RequestMapping(value = "/edit", produces = "text/html;charset=utf-8", method = RequestMethod.GET)
    public String edit(@ModelAttribute User user, Model model) throws Exception{
        model.addAttribute("user",user);
        //超级管理员则需要选择机构，机构管理员只需要选择角色
        model.addAttribute("roles",roleService.getCommonRoles());
        return "/sys/user/edit";
    }

    /**
     * 更新用户信息
     * @param user
     * @return
     * @throws Exception
     */
    @RequiresPermissions("sys:user:edit")
    @RequestMapping(value = "/edit", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> edit(@ModelAttribute User user){
        Map<String,Object> result = new HashedMap();
        Role role=roleService.selectById(user.getRid());
        if(role!=null){
            user.setType(role.getName());
        }
        try {
            if(user.getId() != null && user.getId() > 0){
                userService.updateById(user);
            }else {
                User temp=userService.getByAccount(user.getAccount());
                if(temp!=null){
                    result.put("status",500);
                    result.put("msg","该账号已经存在!");
                    return result;
                }else{
                    userService.insertUser(user,getCurrentUser());
                }
            }
            result.put("status",200);
            result.put("msg","用户信息保存成功");
        }catch (Exception e){
            e.printStackTrace();
            result.put("status",500);
            result.put("msg","用户信息保存失败");
        }
        return result;
    }

    @RequiresPermissions("sys:user:editPw")
    @RequestMapping(value = "/editPw", produces = "text/html;charset=utf-8", method = RequestMethod.GET)
    public String editPw(@ModelAttribute User user, Model model) throws Exception{
        model.addAttribute("user",user);
        return "/sys/user/editPw";
    }

    /**
     * 修改用户密码
     * @param oldPw
     * @param newPw
     * @param repeatPw
     * @return
     * @throws Exception
     */
    @RequiresPermissions("sys:user:editPw")
    @RequestMapping(value = "/editPw", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> editPw(String oldPw, String newPw, String repeatPw){
        Map<String,Object> result = new HashedMap();
        try {
            User cUser = getCurrentUser();
            userService.updatePw(cUser,oldPw,newPw,repeatPw);
            SecurityUtils.getSubject().logout();
            result.put("status",200);
            result.put("msg","用户密码修改成功，请重新登录");
        }catch (Exception e){
            e.printStackTrace();
            result.put("status",500);
            result.put("msg","个人密码更新失败，" + e.getMessage());
        }
        return result;
    }

    /**
     * 删除用户
     * @param id
     * @return
     * @throws Exception
     */
    @RequiresPermissions("sys:user:delete")
    @RequestMapping(value = "/delete", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> delete(Long id){
        Map<String,Object> result = new HashedMap();
        try {
            if(id != null && id > 0){
                userService.deleteById(id);
                result.put("status",200);
                result.put("msg","删除用户成功");
            }else {
                result.put("status",500);
                result.put("msg","请选择删除的用户");
            }
        }catch (Exception e){
            e.printStackTrace();
            result.put("status",500);
            result.put("msg","删除用户失败");
        }
        return result;
    }


    //@RequiresPermissions("sys:user:org")
    @RequestMapping(value = "/org", produces = "text/html;charset=utf-8", method = RequestMethod.GET)
    public String org(@ModelAttribute User user, Model model) throws Exception{
        model.addAttribute("orgs",orgService.selectAll());
        return "/sys/user/org";
    }

    //@RequiresPermissions("sys:user:edit")
    @RequestMapping(value = "/org", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> editOrg(@ModelAttribute User user, @RequestParam("isManager") Boolean isManager){
        Map<String,Object> result = new HashedMap();
        try {
            if(isManager.equals(Boolean.TRUE)){
                user.setRid(ConstantRole.ROLE_ORGANIZATION_ADMIN);
                user.setType("机构管理员");
            }else{
                user.setRid(null);
            }
            userService.updateById(user);
            result.put("status",200);
            result.put("msg","用户信息保存成功");
        }catch (Exception e){
            e.printStackTrace();
            result.put("status",500);
            result.put("msg","用户信息保存失败");
        }
        return result;
    }

    @RequestMapping(value = "/register", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> register(User user, ClientInfo clientInfo){
        Map<String,Object> result = new HashedMap();
        user.setRid(ConstantRole.ROLE_CUSTOM);
        user.setAccount(user.getTelephone());//电话作为登录账号
        user.setPassword(new Md5Utils().getkeyBeanofStr(user.getPassword()));
        try{
            User temp=userService.selectByAccount(user.getAccount());
            if(temp!=null){
                result.put("status",500);
                result.put("msg","该账号已存在");
            }else{
                userService.register(user,clientInfo);
                SecurityUtils.getSubject().login(new UsernamePasswordToken(user.getAccount(), user.getPassword()));
                session.setAttribute(ConstantWebContext.request_cUser, user);

                result.put("status",200);
                result.put("msg","注册成功");
            }
        }catch (Exception e){
            e.printStackTrace();
            result.put("status",500);
            result.put("msg","注册过程中出现异常!");
        }
        return result;
    }

    @RequestMapping(value = "/update", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> frontUpdate(Client client){
        Map<String,Object> result = new HashedMap();
        try{
            User user = userService.selectById(client.getUserId());
            ClientInfo clientInfo = clientInfoService.selectById(client.getId());
            if(user!=null&&clientInfo!=null){
                user.setUsername(client.getUsername());
                user.setEmail(client.getEmail());
                clientInfo.setDueDate(client.getDueDate());
                clientInfo.setExpectedCity(client.getExpectedCity());
                userService.updateById(user);
                clientInfoService.updateById(clientInfo);
            }
            User currentUser = userService.selectById(client.getUserId());
            log.info("currentUser:"+currentUser);
            session.setAttribute(ConstantWebContext.request_cUser, currentUser);
            result.put("status",200);
            result.put("msg","更新成功");
        }catch (Exception e){
            result.put("status",500);
            result.put("msg","修改过程中出现异常!");
        }
        return result;
    }

}

